/**
 * 2013-6-23 下午9:54:02 Created By niexiaoqiang
 */

package com.xiaoqiang.MtwV2ForMoblie;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import android.os.Environment;

import com.xiaoqiang.util.CrashHandler;
import com.xiaoqiang.util.Logger;
import com.xiaoqiang.util.MtwProperties;
import com.xiaoqiang.util.mtwmail.MtwMailSender;

/**
 * 程序启动动作
 */
public class AppStartAction {
    
    public static String MTWROOTDIR;
    
    private MtwProperties mtwProperties;
    
    private static Logger Log = new Logger(AppStartAction.class);
    
    private MainActivity mainActivity;
    
    public AppStartAction(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        MTWROOTDIR = Environment.getExternalStorageDirectory() + File.separator
                     + "mtw";
        try {
            mtwProperties = MtwProperties.newInstance();
        }
        catch (IOException e) {
            Log.error(e);
        }
    }
    
    /**
     * 执行程序启动
     */
    public void run() {
        // 设置程序的版本号
        setAppversion();
        // 设置程序配置文件下载地址
        SetConfigfilelocation();
        // 先删除旧的再发送
        deleteOldCrashFile();
        // 发送Crashfile
        sendCrashReportsToReportMtw();
        // 下载配置文件
        downloadServerConfigFile();
    }
    
    private void downloadServerConfigFile() {
        new MtwDownloadConfigFileThread(mainActivity).start();
    }
    
    /**
     * 设置程序版本号
     */
    private void setAppversion() {
        setProperties("MtwVersion", MainActivity.MTWVERSION);
    }
    
    /**
     * 设置程序配置文件下载地址
     */
    private void SetConfigfilelocation() {
        setProperties("configfilelocation",
                      "https://mtwpublish.googlecode.com/svn/trunk/update/mtwInfo.properties");
        // setProperties("configfilelocation",
        // "http://192.168.1.119:8080/mtwweb/mtwInfo.properties");
    }
    
    /**
     * 删除
     */
    private void deleteOldCrashFile() {
        String allfiles_str = mtwProperties.getProperties("DeleteFiles");
        if (null == allfiles_str || "".equals(allfiles_str)) {
            return;
        }
        String[] allfiles = allfiles_str.trim().split(",");
        for (String path_str : allfiles) {
            new File(path_str).delete();
        }
        setProperties("DeleteFiles", "");
    }
    
    /**
     * 把错误报告发送给服务器,包含新产生的和以前没发送的.
     * 
     * @param ctx
     * @throws FileNotFoundException
     */
    private void sendCrashReportsToReportMtw() {
        String[] crFiles = getCrashReportFiles();
        if (crFiles.length < 1) {
            setProperties("DeleteFiles", "");
            return;
        }
        StringBuffer sb = new StringBuffer();
        ArrayList<String> fileslist = new ArrayList<String>();
        for (String filename : crFiles) {
            String crashFilepath = MTWROOTDIR + File.separator + filename;
            sb.append(crashFilepath + ",");
            fileslist.add(crashFilepath);
        }
        MtwMailSender mail = new MtwMailSender("Application Crash log",
                                               "Application Crash Log",
                                               "reportmtw@gmail.com",
                                               fileslist);
        mail.send();
        setProperties("DeleteFiles", sb.toString());
    }
    
    /**
     * 获取错误报告文件名
     * 
     * @param ctx
     * @return
     */
    private String[] getCrashReportFiles() {
        File filesDir = new File(MTWROOTDIR);
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(CrashHandler.CRASH_REPORTER_EXTENSION);
            }
        };
        return filesDir.list(filter);
    }
    
    /**
     * 设置配置属性
     * 
     * @param key
     * @param value
     */
    private void setProperties(String key, String value) {
        try {
            mtwProperties.setProperties(key, value);
        }
        catch (FileNotFoundException e) {
            Log.error(e);
        }
    }
}
